<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { View, ChatDotRound, StarFilled } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import postsApi, { type Post } from '@/api/posts';
import { useApartmentUserStoreHook } from '@/store/modules/apartmentUser';

defineOptions({
  name: "UserPosts"
});

const router = useRouter();
const loading = ref(false);
const posts = ref<Post[]>([]);
const apartmentUserStore = useApartmentUserStoreHook();
const totalPosts = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 获取用户发帖
const fetchUserPosts = async () => {
  loading.value = true;
  try {
    const userPosts = await postsApi.getCurrentUserPosts();
    posts.value = userPosts;
    totalPosts.value = userPosts.length;
    console.log('User posts loaded:', userPosts);
  } catch (error) {
    console.error('Failed to fetch user posts:', error);
    ElMessage.error('获取帖子列表失败');
  } finally {
    loading.value = false;
  }
};

// 格式化时间
const formatTime = (time: Date | string | undefined): string => {
  if (!time) return '';
  
  const date = new Date(time);
  
  // Format: YYYY-MM-DD HH:MM:SS
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 处理帖子操作
const handleViewPost = (postId: string) => {
  router.push({
    path: '/posts/detail',
    query: { pid: postId }
  });
};

const handleDeletePost = async (postId: string) => {
  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
      '确定要删除这篇帖子吗？删除后无法恢复！',
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    // 用户确认后，执行删除操作
    await postsApi.deletePost(postId);
    ElMessage.success('帖子删除成功');
    // 重新获取用户帖子列表
    fetchUserPosts();
  } catch (error) {
    // 如果是用户取消操作，不显示错误信息
    if (error === 'cancel') {
      return;
    }
    
    console.error('删除帖子失败:', error);
    ElMessage.error('删除帖子失败');
  }
};

const handleEditPost = (postId: string) => {
  ElMessage.info('编辑功能暂未实现');
  // 实际应用中应跳转到编辑页面
};

const handleNewPost = () => {
  router.push('/posts/publish');
};

// 获取帖子的分类标签
const getCategoryLabel = (categoryValue: string): string => {
  const categories = [
    { value: 'apartment', label: '公寓信息' },
    { value: 'roommate', label: '室友寻找' },
    { value: 'experience', label: '居住体验' },
    { value: 'question', label: '问题咨询' },
    { value: 'other', label: '其他' },
  ];
  const category = categories.find(c => c.value === categoryValue);
  return category ? category.label : '其他';
};

onMounted(() => {
  fetchUserPosts();
});
</script>

<template>
  <div class="user-posts-container">
    <div class="user-posts-card">
      <div class="card-header">
        <h1>我的发帖记录</h1>
        <el-button type="primary" icon="Plus" @click="handleNewPost">发布新帖</el-button>
      </div>

      <div class="posts-content" v-loading="loading">
        <el-empty v-if="!loading && posts.length === 0" description="暂无发帖记录"></el-empty>
        
        <div v-else class="posts-list">
          <el-card v-for="post in posts" :key="post.id" class="post-card" shadow="hover">
            <template #header>
              <div class="post-header">
                <h3 class="post-title" @click="handleViewPost(post.id)">{{ post.title }}</h3>
                <div class="post-actions">
                  <el-button type="primary" text @click="handleEditPost(post.id)">编辑</el-button>
                  <el-button type="danger" text @click="handleDeletePost(post.id)">删除</el-button>
                </div>
              </div>
            </template>
            
            <div class="post-content">
              <p class="post-text">{{ post.content.length > 150 ? post.content.substring(0, 150) + '...' : post.content }}</p>
              
              <div class="post-tags">
                <el-tag size="small" class="post-tag">{{ getCategoryLabel(post.category) }}</el-tag>
              </div>
              
              <div class="post-meta">
                <div class="post-time">发布于：{{ formatTime(post.createdAt) }}</div>
                <div class="post-stats">
                  <span class="stat-item"><el-icon><View /></el-icon> {{ post.viewCount }}</span>
                  <span class="stat-item"><el-icon><ChatDotRound /></el-icon> {{ post.commentCount }}</span>
                  <span class="stat-item"><el-icon><StarFilled /></el-icon> {{ post.likeCount }}</span>
                </div>
              </div>
            </div>
          </el-card>
        </div>
        
        <div class="pagination-container" v-if="posts.length > 0">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="totalPosts"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="currentPage = $event"
            class="pagination"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.user-posts-container {
  padding: 20px 30px;
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  
  .user-posts-card {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    overflow: hidden;
    width: 100%;
    max-width: 1000px;
    
    .card-header {
      padding: 20px 24px;
      border-bottom: 1px solid #f0f0f0;
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-wrap: wrap;
      
      h1 {
        margin: 0;
        font-size: 20px;
        color: #303133;
        font-weight: 500;
      }
      
      @media (max-width: 480px) {
        flex-direction: column;
        align-items: flex-start;
        
        h1 {
          margin-bottom: 12px;
        }
      }
    }
    
    .posts-content {
      padding: 24px;
      
      .posts-list {
        display: flex;
        flex-direction: column;
        gap: 20px;
        
        .post-card {
          border-radius: 8px;
          transition: transform 0.3s;
          
          &:hover {
            transform: translateY(-3px);
          }
          
          .post-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            
            .post-title {
              margin: 0;
              font-size: 18px;
              font-weight: 500;
              color: #303133;
              cursor: pointer;
              
              &:hover {
                color: #409eff;
              }
            }
            
            .post-actions {
              display: flex;
              gap: 8px;
            }
            
            @media (max-width: 480px) {
              flex-direction: column;
              align-items: flex-start;
              
              .post-title {
                margin-bottom: 8px;
              }
              
              .post-actions {
                align-self: flex-end;
              }
            }
          }
          
          .post-content {
            .post-text {
              color: #606266;
              line-height: 1.6;
              margin-bottom: 16px;
            }
            
            .post-tags {
              display: flex;
              flex-wrap: wrap;
              gap: 8px;
              margin-bottom: 16px;
              
              .post-tag {
                border-radius: 4px;
              }
            }
            
            .post-meta {
              display: flex;
              justify-content: space-between;
              color: #909399;
              font-size: 14px;
              
              .post-stats {
                display: flex;
                gap: 16px;
                
                .stat-item {
                  display: flex;
                  align-items: center;
                  gap: 4px;
                }
              }
              
              @media (max-width: 480px) {
                flex-direction: column;
                gap: 8px;
                
                .post-stats {
                  justify-content: flex-end;
                }
              }
            }
          }
        }
      }
      
      .pagination-container {
        margin-top: 32px;
        display: flex;
        justify-content: center;
      }
    }
  }
}
</style> 